<script lang="ts"
        setup>
import {Check, Close} from '@element-plus/icons-vue'
import {computed, markRaw, onBeforeMount, ref} from 'vue'
import {getArticleByIdApi, addOrUpdateArticleApi} from '../../apis/article'
import {getSortsApi} from '../../apis/sort'
import {getLabelsApi} from '../../apis/label'
import "mavon-editor/dist/css/index.css"
import {useRouter} from "vue-router";
import {Delete, Download, Plus, ZoomIn} from '@element-plus/icons-vue'
import {getResourceListApi} from '../../apis/resource'
import {openMessageBox} from '../../utils/MessageBox'

const $router = useRouter();
import {uploadImageApi} from '../../apis/qiniu'
import {ElMessage, ElMessageBox} from "element-plus";
import {api as viewerApi} from "v-viewer";

const editor = ref(null)
const article = ref({
  id: '',
  articleContent: '',
  userId:1,
  sortId: 1,
  labelId: 1,
  userName: 'admin',
  labelName: '',
  sortName: '',
  articleCover: '',
  articleTitle: '',
  viewStatus: 1,
  commentStatus: 1,
  deleted: 0,
  articleRender: ''
})
const isEditMode = ref(true)
const resourceList = ref([])
const fileName = ref('')
onBeforeMount(async () => {
  const articleId = $router.currentRoute.value.query.articleId as string;
  isEditMode.value = $router.currentRoute.value.query.isEditMode as boolean;
  // 有id则为修改否则为添加
  if (articleId) {
    article.value.id = articleId
    article.value = (await getArticleByIdApi(articleId)).data
  }


})


const sortList = ref([])
const labelList = ref([])
const imgAdd = async (position, file) => {
  const formData = new FormData()
  formData.append('file', file)
  const data = (await uploadImageApi(formData, '11', 2)).data
  editor.value.$img2Url(position, data + '?imageView2/2/w/400')
}
const saveContent = (value, render) => {
  article.value.articleContent = value
  article.value.articleRender = render
  ElMessage.success('保存内容成功,请输入必要的信息')
  drawerVisible.value = !drawerVisible.value
}

const saveArticle = async () => {
  console.log('ar',article.value)
  const res = await addOrUpdateArticleApi(article.value)

  if (res.status) {
    ElMessage({
      message: '保存成功',
      type: 'success',
      duration: 1000
    })
    drawerVisible.value = !drawerVisible.value
    await $router.push('/article/list')
  }
}

const drawerVisible = ref(false)

const handleDrawerOpen=async ()=>{
  sortList.value = (await getSortsApi()).data
  labelList.value = (await getLabelsApi()).data

  resourceList.value = (await getResourceListApi()).data
  console.log('r', sortList.value)
  console.log('r1', labelList.value)
}
const handleDrawerClose = (done) => {
  ElMessageBox.confirm('确定不保存直接退出吗?')
      .then(() => {
        done()
      })
      .catch(() => {
        // catch error
      })
}

const handlePreview = (file) => {
  if (!file.url) {
    return
  } else {
    viewerApi({
      images: file.url
    })
  }
}

const onBeforeUpload =async () => {

   fileName.value=<string>await openMessageBox('请输入文件标签',
       (value) => value !== null, markRaw(Delete),
       `确定`,
       'Input canceled'
   )


}

const onCoverUploadSuccess = async (response, uploadFile, uploadFiles) => {
  article.value.articleCover = response.data.resourceValue
  console.log( response.data.resourceValue)
  resourceList.value = (await getResourceListApi()).data

}

const fileList = computed(() => {
  if (article.value.articleCover) {
    return [{name: article.value.articleCover, url: article.value.articleCover}]
  }
  return []
})

/**
 * 文件移除之前,删除el-option的选中
 */
const onFileRemove=()=>{
  fileName.value=''
}

import axios from 'axios'
const ans=ref('')
const question=ref('')
const descript=()=>{
  axios.post('/img/', {
    'question': question.value+'，我说的对吗？',
    'index': 2,
    // 'name': 'https://sky-delievery.oss-cn-beijing.aliyuncs.com/20240508-%E5%A4%B1%E7%89%A9%E6%8B%9B%E9%A2%86-725de48a288c491e9c55bdec9cdb88be.jpg'
    'name': article.value.articleCover
  })
      .then(function (response) {
        ans.value = response.data.msg

        console.log(response.data)
      })
      .catch(function (error) {
        console.log(error)
      })
}
</script>

<template>
  <div class="editor-container">

    <mavon-editor
        ref="editor"
        class="editor"
        :ishljs="true"
        v-model="article.articleContent"
        @imgAdd="imgAdd"
        @save="saveContent"
    />
    <el-drawer
        @open="handleDrawerOpen"
        v-model="drawerVisible"
        title="编辑文章"
        direction="rtl"
        :before-close="handleDrawerClose"
    >
      <el-form :model="article"
               label-width="auto"
               style="max-width: 600px">
        <el-form-item label="文章标题">
          <el-input v-model="article.articleTitle"
                    placeholder="请输入文章标题"/>
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select v-model="article.sortId"
                     placeholder="请选择文章分类">
            <el-option v-for="sort in sortList" :label="sort.sortName"
                       :value="sort.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签">
          <el-select v-model="article.labelId"
                     placeholder="请选择文章分类">
            <el-option v-for="label in labelList" :label="label.labelName"
                       :value="label.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面">
          <el-upload :action="`/api/qiniu/upload/${fileName}/2`"
                     :limit="1"
                     :on-remove="onFileRemove"
                     :before-upload="onBeforeUpload"
                     :on-success="onCoverUploadSuccess"
                     list-type="picture-card"
                     v-model:file-list="fileList"
                     :auto-upload="true">
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
          <el-select placeholder="从资源文件获取"
                     value-key="resourceLabel"
                     v-model="article.articleCover">
            <el-option
                v-for="item in resourceList"
                :key="item.resourceKey"
                :label="item.resourceLabel"
                :value="item.resourceValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章作者">
          <el-input v-model="article.userName"
                    disabled/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="saveArticle">保存文章
          </el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="descript">描述</el-button>
      <el-input v-model="question" placeholder="请输入问题"></el-input>
      <div>{{ans}}</div>

    </el-drawer>
  </div>
</template>

<style lang="scss"
       scoped>
@import "mavon-editor/dist/css/index.css";

.editor-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;

  :deep(.html) {
    //h1 {
    //  color: orchid;
    //}
    //h2{
    //  background-color: orchid;
    //  color: red;
    //}
  }

  .base-container {
    width: 100%;
    height: 200px;
  }

  .editor {
    width: 80%;
    height: 100%;

  }
}


</style>
